﻿using DryIoc;
using DryIoc.Microsoft.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Prism.DryIoc;
using Prism.Ioc;
using Prism.Regions;
using System.Windows;
using VisionApp.PostProcess.Net8;
using VisionApp.PreProcess.Net8;
using VisionApp.Startup.Services;
using VisionApp.Startup.Views;
using VisionApp.UserManager.Service;

namespace VisionApp.Startup
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App: PrismApplication
    {
        // 定义一个唯一的互斥体名称
        private const string MutexName = "1A1A4FF6 - 909E-400E - 81C0 - 02B8684B39EF";
        private Mutex _mutex;

        protected override void OnStartup(StartupEventArgs e)
        {
            bool createNew;
            _mutex=new Mutex(true, MutexName, out createNew);
            if (!createNew) { 
            MessageBox.Show("程序已在运行中！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                var currentProcess = System.Diagnostics.Process.GetCurrentProcess();
                foreach (var process in System.Diagnostics.Process.GetProcessesByName(currentProcess.ProcessName))
                {
                    if (process.Id != currentProcess.Id)
                    {
                        IntPtr mainWindowHandle = process.MainWindowHandle;
                        if (mainWindowHandle != IntPtr.Zero)
                        {
                            // 激活窗口到前台
                            NativeMethods.SetForegroundWindow(mainWindowHandle);
                        }
                        break;
                    }
                }
                Shutdown();
                return;
            }
            base.OnStartup(e);
        }

        // 用于激活窗口的本地方法
        internal static class NativeMethods
        {
            [System.Runtime.InteropServices.DllImport("user32.dll")]
            internal static extern bool SetForegroundWindow(IntPtr hWnd);
        }

        protected override Window CreateShell()
        {
            var shell=Container.Resolve<MainWindow>();
            return shell;
        }
        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterForNavigation<MainWindow>();
            containerRegistry.RegisterForNavigation<OneCameraLayoutView>("1");
            containerRegistry.RegisterForNavigation<TwoCameraLayoutView>("2");
            containerRegistry.RegisterForNavigation<ThreeCameraLayoutView>("3");
            containerRegistry.RegisterForNavigation<FourCameraLayoutView>("4");
            containerRegistry.RegisterForNavigation<SixCameraLayoutView>("6");
            containerRegistry.RegisterForNavigation<EightCameraLayoutView>("8");
            containerRegistry.RegisterForNavigation<TwelveCameraLayoutView>("12");
        }
        protected override IContainerExtension CreateContainerExtension()
        {
            var serviceCollection = new ServiceCollection();

            // 注册配置文件
            var builder = new ConfigurationBuilder();
            builder.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                .AddJsonFile("appsettings.json", true, true);

            var configuration = builder.Build();

            serviceCollection.AddSingleton<IConfiguration>(configuration);

            // 注册日志服务
            serviceCollection.AddLogging(cfg =>
            {
                cfg.ClearProviders();
                cfg.SetMinimumLevel(LogLevel.Trace);
                cfg.AddNLog();
            });

            // 注册其他服务
            serviceCollection.AddSingleton<AlgoManager>();
            serviceCollection.AddSingleton<CommunicationService>();

            serviceCollection.AddUserManagerService();
            serviceCollection.AddPreProcess();
            serviceCollection.AddPostProcess();

            var container = new Container(CreateContainerRules());
            return new DryIocContainerExtension(container.WithDependencyInjectionAdapter(serviceCollection));
        }
        protected override async void OnInitialized()
        {
            var splash = Container.Resolve<SplashScreen>();
            splash.Show();

            splash.SplashCompleted += (s, e) =>
            {
                base.OnInitialized();
        };

        // 导航到主内容区域
        var configuration = Container.Resolve<IConfiguration>();
            string startupViewName = configuration.GetValue<string>("StartupView");
            var regionManager = Container.Resolve<IRegionManager>();
            regionManager.RequestNavigate("MainContentRegion", startupViewName);

            // 启动MQTT服务
            //var mqtt = Container.Resolve<IMqttService>();
            //await mqtt.StartServerAsync();
            //await mqtt.StartLoggerClientAsync();
        }

        protected override void OnExit(ExitEventArgs e)
        {
            base.OnExit(e);
        }
    }
}
